// 定义和餐食相关的接口
const Router = require('koa-router')
const router = new Router()
const { getDietData, writeFoodData, deleteFoodData } = require('../controllers/index.js')
const { verify } = require('../utils/jwt.js')

router.prefix('/diet')

// 获取用户每日的餐食
router.get('/getDietData', verify(), async (ctx, next) => {
    const user_id = ctx.user_id
    const { time } = ctx.query
    const res = await getDietData(user_id, time)
    try {
        if (res.length) {
            ctx.body = {
                code: 200,
                data: res,
                msg: '获取成功',
            }
        } else {
            ctx.body = {
                code: 200,
                data: [],
                msg: '暂无数据',
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }
})

// 写入一条食物数据
router.post('/writeFoodData', verify(), async (ctx, next) => {
    const user_id = ctx.user_id
    const { component, time, create_time } = ctx.request.body
    // console.log(user_id, component, time, create_time);
    const res = await writeFoodData(user_id, component, time, create_time)
    // console.log(res);
    try {
        if (res.affectedRows) {
            ctx.body = {
                code: 200,
                msg: '添加成功',
            }
        } else {
            ctx.body = {
                code: 200,
                msg: '添加失败',
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }
})

// 删除一条食物数据
router.get('/deleteFoodData', async (ctx, next) => {
    const { id } = ctx.query
    // console.log(id);
    const res = await deleteFoodData(id)
    // console.log(res);
    try {
        if (res.affectedRows) {
            ctx.body = {
                code: 200,
                msg: '删除成功',
            }
        } else {
            ctx.body = {
                code: 200,
                msg: '删除失败',
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }
})

module.exports = {
    dietRouter: router
}